﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using Facebook;
using BLL = KC.Business.BlogSlinger;
using DAL = KC.DataAccess.BlogSlinger;

public partial class site : System.Web.UI.MasterPage
{
	protected void Page_PreRender(object sender, EventArgs e)
	{
		lblRenderTime.Text = (DateTime.Now - dtRenderStart).TotalMilliseconds.ToString("###,###.##");
		if (Page.MetaKeywords.Length > 512)
			Page.MetaKeywords = Page.MetaKeywords.Substring(0, 512);
		if (Page.MetaDescription.Length > 512)
			Page.MetaDescription = Page.MetaDescription.Substring(0, 507) + "[...]";
	}
	protected void Page_Init(object sender, EventArgs e)
	{
		dtRenderStart = DateTime.Now;
		lblErr.Text = "";
		try { Login(); }
		catch (FacebookAPIException) { } // TODO: log error
		if (user == null)
		{
			hlLogin.NavigateUrl = "https://graph.facebook.com/oauth/authorize?client_id=156267124416417&display=popup&scope=publish_stream,user_website,email&redirect_uri=" + Server.UrlEncode("http://blogs.code-slinger.com/");
			hlLogin.Text = "Login";
		}
		else
		{
			lblErr.Text = "Logged in as " + user.FacebookName;
			hlLogin.Text = "Logout";
			hlLogin.NavigateUrl = "javascript:FB.logout();";
		}
	}
	protected void Page_Load(object sender, EventArgs e)
	{
		SelectMenuNode();

		if (user != null && user.ID > 0)
			pnlAdsense1.Visible = false;
	}
	protected void btnSearch_Click(object sender, EventArgs e)
	{
		if (string.IsNullOrEmpty(txtSearch.Text.Trim()))
			return;
		Response.Redirect("Search.aspx?query=" + Server.UrlEncode(txtSearch.Text), false);
	}

	public DAL.BlogSlingerDataContext dc = new DAL.BlogSlingerDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["SQL"].ConnectionString);
	public FacebookAPI api = new FacebookAPI(null);
	public string
		userid = null,
		token = null;
	public DAL.User user;
	private DateTime dtRenderStart;

	private void SelectMenuNode()
	{
		// Get the current page, the whole page, and nothing but the page.  Just the Fax, ma'am.
		string page = Request.RawUrl.Substring(Request.RawUrl.LastIndexOf('/') + 1);
		if (page.Contains('?')) page = page.Substring(0, page.IndexOf('?'));

		int index = 0;
		switch (page.ToLower())
		{
			case "":
			case "default.aspx":
			default:
				index = 0; break;
			case "about.aspx":
			case "legal.aspx":
				index = 1; break;
			case "browse.aspx":
			case "post.aspx":
			case "blog.aspx":
			case "search.aspx":
				index = 2; break;
			case "admin.aspx":
				index = 3; break;
		}

		// Update styles appropriately
		tMenu.Rows[0].Cells[index].Style.Add("border-bottom", "solid 1px #ffffff");
		tMenu.Rows[0].Cells[index].Style.Add("border-top", "solid 3px #565656;");
	}
	private void Login()
	{
		if (Request.UserHostAddress == "127.0.0.1") {
			user = (from u in dc.Users where u.ID == 3 select u).First();
			return; }

		if (user == null)
			LoginOldSession();
		if (user == null)
			LoginNewSession();
	}
	private void LoginOldSession()
	{

	}
	private void LoginNewSession()
	{
		if (Session["User"] != null)
		{
			user = (DAL.User)Session["User"];
			return;
		}

		if (!string.IsNullOrEmpty(token) && api.AccessToken != token)
			api = new FacebookAPI(token);
		string redUrl = HttpUtility.UrlEncode("http://blogs.code-slinger.com/");
		// User detected as not logged in; redirect to the first FB login

		token = token ?? (string)Session["token"];
		if (!string.IsNullOrEmpty(token))
			return;

		// FB wants its code and refuses to give auth token on first postback. Whiny little bitch.
		bool isNewLogin = false;
		if (Request.Url.AbsoluteUri.Contains("code="))
		{
			isNewLogin = true;
			string clientId = "156267124416417", clientSecret = "39fbd269f3b63d90afca00e3ca0c7463", code = Request.QueryString["code"];

			WebClient wc = new WebClient();
			string result = "";
			try { result = wc.DownloadString("https://graph.facebook.com/oauth/access_token?client_id=" + clientId + "&display=popup&scope=publish_stream&redirect_uri=" + redUrl + "&client_secret=" + clientSecret + "&code=" + code); }
			catch (System.Net.WebException ex)
			{
				StreamReader readStream = new StreamReader(ex.Response.GetResponseStream());
				string err = readStream.ReadToEnd() + result; // TODO: Use err
				return;
			}
			token = BLL.DecodeToken(result);
			if (string.IsNullOrEmpty(token))
				return;

			if (string.IsNullOrEmpty(api.AccessToken))
				api.AccessToken = token;
			userid = api.Get("/me").Dictionary["id"].String;
			Session["token"] = token;
		}
		if (string.IsNullOrEmpty(userid))
			return;

		try
		{
			user = BLL.RecordLogin(ref dc, userid, api.Get("/me").Dictionary["name"].String, token);
			Session["user"] = user;
		}
		catch
		{ // TODO: Log error
			UpdateErr("Sorry, but there was an error logging you in.");
		} 
		if (isNewLogin && user != null)
		{
			UpdateErr("Logged in as " + user.FacebookName);
			BLL.LogActivity(ref dc, user, Request.UserHostAddress, "Logged in", "Logged in as " + user.FacebookName, Request.Url.AbsoluteUri, (Request.UrlReferrer != null ? Request.UrlReferrer.AbsoluteUri : ""));
		}
	}
	public void UpdateErr(string err)
	{
		lblErr.Text = err;
	}
}
